#读取数据
library(Seurat)
data_dir <- "D:/Rstudio file/hg19" 
counts <- Read10X(data.dir = data_dir)  
#初始化Seurat对象  
pbmc<- CreateSeuratObject(counts = counts,project = "pbmc3k",
                          min.cells = 3,min.features = 200)#min.cells至少3个细胞中检测到表达基因
# 过滤
pbmc[["percent.mt"]]<-PercentageFeatureSet(pbmc,pattern = "^MT-")#线粒体基因比例（percent.mt）
          #计算了pbmc中每个细胞的线粒体基因（以"^MT-"开头的基因）的百分比，并将这个百分比存储在seurat_obj的percent.mt元数据中。
pbmc<-subset(pbmc,subset = nFeature_RNA>200 & nFeature_RNA<2500 & percent.mt<5)#从pbmc对象中选取那些nFeature_RNA（即每个细胞中检测到的基因数量）大于200且小于2500的细胞。
# 归一化和标准化  
pbmc <- NormalizeData(pbmc, normalization.method = "LogNormalize", scale.factor = 10000)
pbmc<-FindVariableFeatures(pbmc,selection.method = "vst",nfeatures = 2000)
# 降维与聚类
pbmc<-ScaleData(pbmc,features = row.names(pbmc))
pbmc<-RunPCA(pbmc)#使用前100个主成分  
pbmc<-FindNeighbors(pbmc,dims = 1:10)# 基于前10个主成分来定义邻居
pbmc<-FindClusters(pbmc,resolution =0.5)# 使用0.5的分辨率进行聚类 
pbmc<-RunUMAP(pbmc,dims = 1:10)#使用前10个主成分进行UMAP降维
# 绘制UMAP图
DimPlot(pbmc,reduction = "umap")
# 鉴定marker,并选出前两个genescluster的Top 2
markergene<-FindAllMarkers(pbmc,only.pos = TRUE,min.pct = 0.25,logfc.threshold = 0.25)
library(dplyr)
top2<- markergene%>%#%>% 是管道操作符，它将左侧的对象传递给右侧的函数作为第一个参数
  group_by(cluster) %>%  
  slice(1:2) %>%  # 直接取每个cluster的前两行  
  ungroup() %>%  # 移除分组  
  select(cluster,gene)  # gene列  
# 绘制每个基因气泡图  
DotPlot(pbmc,features=top2$gene)+RotatedAxis()
# FeaturePlot  
FeaturePlot(pbmc, features = top2$gene)  
# VlnPlot  
VlnPlot(pbmc, features = top2$gene)

